package com.ruoyi.controller;

import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.minio.server.MinioService;
import com.ruoyi.entity.ActivityDetailDto;
import com.ruoyi.product.domain.ProductActivity;
import com.ruoyi.product.domain.ProductImage;
import com.ruoyi.product.domain.VerActivitySkuRelate;
import com.ruoyi.service.ProductActivitysService;
import jakarta.annotation.Resource;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/activity")
public class ProductActivityController extends BaseController {
    @Resource
    private ProductActivitysService activityService;

    @Autowired
    private MinioService minioService;

    @Value("${minio.bucket-name}")
    private String bucketName;

    /**
     * 删除活动
     */
    @DeleteMapping("/delete/{activityIds}")
    public AjaxResult deleteActivity(@PathVariable Long[] activityIds) {
        try {
            // 先获取活动信息，用于删除图片
            for (Long activityId : activityIds) {
                ProductActivity activity = activityService.getActivityDetail(activityId);
                if (activity != null) {
                    // 删除MinIO中的活动海报图片
                    String posterUrl = activity.getPosterUrl();
                    if (posterUrl != null && !posterUrl.isEmpty()) {
                        try {
                            // 提取文件名，URL格式为 http://minio-server/bucket-name/filename
                            String fileName = posterUrl.substring(posterUrl.lastIndexOf("/") + 1);
                            // 删除MinIO中的文件
                            minioService.deleteFile(bucketName, fileName);
                        } catch (Exception e) {
                            logger.error("删除活动海报图片失败: activityId=" + activityId, e);
                        }
                    }
                }
            }

            // 删除活动
            boolean success = activityService.deleteActivityById(activityIds);
            if (success) {
                return AjaxResult.success("活动删除成功");
            } else {
                return AjaxResult.error("活动删除失败，可能活动不存在");
            }
        } catch (Exception e) {
            return AjaxResult.error("删除活动失败：" + e.getMessage());
        }
    }

    /**
     * 上传活动海报图片
     */
    @PostMapping("/{activityId}/upload-poster")
    @SneakyThrows
    public AjaxResult uploadActivityPoster(@PathVariable Long activityId,
                                           @RequestParam("file") MultipartFile file) {
        try {
            // 检查活动是否存在
            ProductActivity activity = new ProductActivity();
            activity.setActivityId(activityId);
            List<ProductActivity> activities = activityService.getAllActivities(activity);
            if (activities.isEmpty()) {
                return AjaxResult.error("活动不存在");
            }

            // 生成文件名
            String originalFileName = file.getOriginalFilename();
            String fileExtension = "";
            if (originalFileName != null && originalFileName.contains(".")) {
                fileExtension = originalFileName.substring(originalFileName.lastIndexOf("."));
            }
            String fileName = "activity_poster_" + activityId + "_" + System.currentTimeMillis() + fileExtension;

            // 上传文件到MinIO
            Map<String, String> uploadResult = minioService.uploadFile(file, fileName);

            if (uploadResult != null && "true".equals(uploadResult.get("success"))) {
                // 更新活动的海报URL
                ProductActivity updateActivity = new ProductActivity();
                updateActivity.setActivityId(activityId);
                updateActivity.setPosterUrl(uploadResult.get("fileUrl"));
                boolean success = activityService.updateActivity(updateActivity);

                if (success) {
                    Map<String, Object> resultMap = new HashMap<>();
                    // 返回给前端
                    resultMap.put("posterUrl", uploadResult.get("fileUrl"));
                    resultMap.put("fileName", fileName);
                    return AjaxResult.success("上传成功", resultMap);
                } else {
                    return AjaxResult.error("更新活动海报URL失败");
                }
            } else {
                return AjaxResult.error("文件上传失败");
            }
        } catch (Exception e) {
            logger.error("上传活动海报失败", e);
            return AjaxResult.error("上传活动海报失败: " + e.getMessage());
        }
    }

    /**
     * 创建活动并上传海报图片
     */
    @PostMapping(value = "/create", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public AjaxResult createActivityWithPoster(
            @RequestPart("activity") ProductActivity activity,
            @RequestPart(value = "file", required = false) MultipartFile file) {
        try {
            // 创建活动
            Long activityId = activityService.createActivity(activity);

            // 如果有上传文件，则处理海报图片
            if (file != null && !file.isEmpty()) {
                // 生成文件名
                String originalFileName = file.getOriginalFilename();
                String fileExtension = "";
                if (originalFileName != null && originalFileName.contains(".")) {
                    fileExtension = originalFileName.substring(originalFileName.lastIndexOf("."));
                }
                String fileName = "activity_poster_" + activityId + "_" + System.currentTimeMillis() + fileExtension;

                // 上传文件到MinIO
                Map<String, String> uploadResult = minioService.uploadFile(file, fileName);

                if (uploadResult != null && "true".equals(uploadResult.get("success"))) {
                    // 更新活动的海报URL
                    ProductActivity updateActivity = new ProductActivity();
                    updateActivity.setActivityId(activityId);
                    updateActivity.setPosterUrl(uploadResult.get("fileUrl"));
                    activityService.updateActivity(updateActivity);

                    Map<String, Object> resultMap = new HashMap<>();
                    resultMap.put("activityId", activityId);
                    resultMap.put("posterUrl", uploadResult.get("fileUrl"));
                    resultMap.put("fileName", fileName);
                    return AjaxResult.success("活动创建成功并上传海报", resultMap);
                } else {
                    // 即使海报上传失败，活动也已经创建成功
                    Map<String, Object> resultMap = new HashMap<>();
                    resultMap.put("activityId", activityId);
                    resultMap.put("message", "活动创建成功但海报上传失败");
                    return AjaxResult.success(resultMap);
                }
            } else {
                // 没有上传文件，只创建活动
                return AjaxResult.success("活动创建成功", activityId);
            }
        } catch (Exception e) {
            return AjaxResult.error("创建活动失败：" + e.getMessage());
        }
    }

    /**
     * 更新活动
     */
    @PutMapping("/update")
    public AjaxResult updateActivity(@RequestBody ProductActivity activity) {
        try {
            boolean success = activityService.updateActivity(activity);
            return AjaxResult.success(success);
        } catch (Exception e) {
            return AjaxResult.error("更新活动失败：" + e.getMessage());
        }
    }

    /**
     * 获取所有活动
     */
    @GetMapping("/getAllActivities")
    public TableDataInfo getAllActivities(ProductActivity activity) {
        try {
            startPage();  // 启用分页
            List<ProductActivity> activities = activityService.getAllActivities(activity);
            return getDataTable(activities);  // 返回分页数据
        } catch (Exception e) {
            // 错误处理需要在调用方处理，或者重新设计返回结构
            throw new RuntimeException("获取活动列表失败：" + e.getMessage(), e);
        }
    }

    /**
     * 获取活动详情
     */
    @GetMapping("/{activityId}")
    public AjaxResult getActivityDetail(@PathVariable Long activityId) {
        try {
            ActivityDetailDto detail = activityService.getActivityDetail(activityId);
            return AjaxResult.success(detail);
        } catch (Exception e) {
            return AjaxResult.error("获取活动详情失败：" + e.getMessage());
        }
    }

    /**
     * 为活动添加商品
     */
    @PostMapping("/{activityId}/sku")
    public AjaxResult addSkuToActivity(
            @PathVariable Long activityId,
            @RequestParam Long skuId,
            @RequestParam BigDecimal price) {
        try {
            boolean success = activityService.addSkuToActivity(activityId, skuId, price);
            return AjaxResult.success(success);
        } catch (Exception e) {
            return AjaxResult.error("添加活动商品失败：" + e.getMessage());
        }
    }

    /**
     * 从活动中移除商品
     */
    @DeleteMapping("/{activityId}/sku/{skuId}")
    public AjaxResult removeSkuFromActivity(
            @PathVariable Long activityId,
            @PathVariable Long skuId) {
        try {
            boolean success = activityService.removeSkuFromActivity(activityId, skuId);
            return AjaxResult.success(success);
        } catch (Exception e) {
            return AjaxResult.error("移除活动商品失败：" + e.getMessage());
        }
    }

    /**
     * 更新活动商品价格
     */
    @PutMapping("/{activityId}/sku/{skuId}/price")
    public AjaxResult updateActivitySkuPrice(
            @PathVariable Long activityId,
            @PathVariable Long skuId,
            @RequestParam BigDecimal price) {
        try {
            boolean success = activityService.updateActivitySkuPrice(activityId, skuId, price);
            return AjaxResult.success(success);
        } catch (Exception e) {
            return AjaxResult.error("更新活动商品价格失败：" + e.getMessage());
        }
    }

    /**
     * 获取活动下的所有商品
     */
    @GetMapping("/{activityId}/skus")
    public AjaxResult getSkusByActivityId(@PathVariable Long activityId) {
        try {
            List<VerActivitySkuRelate> skus = activityService.getSkusByActivityId(activityId);
            return AjaxResult.success(skus);
        } catch (Exception e) {
            return AjaxResult.error("获取活动商品失败：" + e.getMessage());
        }
    }
}
